<template>
  <div class="map-container">
    <div id="map" class="map"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import GeoJSON from 'ol/format/GeoJSON'
import { Style, Stroke, Fill, Text } from 'ol/style'
import { fromLonLat } from 'ol/proj'

export default {
  name: 'GeoJSONDemo',
  data() {
    return {
      map: null,
      vectorLayer: null
    }
  },
  mounted() {
    this.initMap()
    this.loadGeoJSON()
  },
  methods: {
    initMap() {
      // 初始化地图
      this.map = new Map({
        target: 'map',
        layers: [
          // 高德地图作为底图
          new TileLayer({
            source: new XYZ({
              url: 'https://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
              maxZoom: 18
            })
          })
        ],
        view: new View({
          center: fromLonLat([87.617733, 43.792818]), // 乌鲁木齐市中心坐标
          zoom: 6
        })
      })
    },

    async loadGeoJSON() {
      try {
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=650000_full')
        const geoData = await response.json()

        // 创建矢量数据源
        const vectorSource = new VectorSource({
          features: new GeoJSON().readFeatures(geoData, {
            featureProjection: 'EPSG:3857' // Web墨卡托投影
          })
        })

        // 创建矢量图层
        this.vectorLayer = new VectorLayer({
          source: vectorSource,
          style: (feature) => {
            const properties = feature.getProperties();
            // 创建基础样式
            const styles = [
              new Style({
                stroke: new Stroke({
                  color: '#1c28d3',
                  width: 2
                }),
                fill: new Fill({
                  color: 'rgba(25, 118, 210, 0.1)'
                })
              })
            ];
            
            // 如果有name属性，添加文字标注
            if (properties.name) {
              styles.push(
                new Style({
                  text: new Text({
                    text: properties.name,
                    font: '14px sans-serif',
                    fill: new Fill({
                      color: '#333'
                    }),
                    stroke: new Stroke({
                      color: '#fff',
                      width: 2
                    }),
                    // 使用centroid属性作为文字位置
                    textAlign: 'center',
                    textBaseline: 'middle'
                  })
                })
              );
            }
            
            return styles;
          }
        })

        // 添加图层到地图
        this.map.addLayer(this.vectorLayer)

        // 缩放到数据范围
        this.map.getView().fit(vectorSource.getExtent(), {
          padding: [50, 50, 50, 50]
        })
      } catch (error) {
        console.error('加载GeoJSON数据失败:', error)
      }
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.setTarget(null)
      this.map = null
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}
</style> 